<?php

ini_set("memory_limit", "100M");
ini_set("max_execution_time", 36000);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Alliance.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'class/db/DBAlliance.class.php');
require_once(SITE_ROOT . 'class/db/DBAllianceMember.class.php');
require_once(SITE_ROOT . 'class/logic/LogicCoolness.class.php');

try {
	if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");
	
	if (isset($_GET['alliance'])) {
		if (preg_match("/^[0-9]{1,7}$/", $_GET['alliance'])) {
			$allianceID = $_GET['alliance'];
		}
		else die("AllianceID may only contain numbers!");
	}
	else die("AllianceID must be set!");
	
	$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET);
	$HT->setOauthToken(USERTOKEN);
	$HT->setOauthTokenSecret(USERTOKENSECRET);
	
	$_SESSION['HT'] = $HT;
	
	$dballiance = new DBAlliance();
	$dballiancemember = new DBAllianceMember();
	$logic = LogicCoolness::getInstance();
	$count = 0;
	
	$alliance = $dballiance->getAllianceByID($allianceID);
			
	$teams = $dballiancemember->getAllianceMembershipByAlliance($alliance);
	foreach ($teams as $team) {
		try {
			$logic->autoUpdate($team->getTeamID(), false);
			$count++;
			if ($count == 100) {
				$HT->clearTeams();
				$count = 0;
			}
		}
		catch (IsBotException $ibe) {}
		catch (LeagueNotAvailableException $lnae) {}
		catch (Exception $e) {
			echo "Update failed at team " . $team->getTeamID() . "<br />";
		}
	}
	echo "Update was successfull!";
}
catch (Exception $e) {
	echo $e->getMessage();
}

?>